import { request, getFileRequest } from '@/api/core/http'
import { IParmasMsgHistory } from './types'
// 创建机器人会话产生的toekn
export const getToken = () => {
  return localStorage.getItem('ai_chat_token') || ''
}

/**
 * 发起会话
 * @param ai_user_id number 机器人id
 */
export const creatAiChat = (ai_user_id: number) => {
  return request.post('/platform/api/aichat/h5/chat', { ai_user_id })
}

/**
 * 发送消息
 * @param content string 消息
 * @param ai_user_id number 机器人id
 */
export const sendMsg = (content: string, ai_user_id: number) => {
  return request
    .post(
      '/platform/api/aichat/h5/sendMsg',
      { content, ai_user_id },
      {
        headers: {
          Authorization: `Bearer ${getToken()}`,
        },
      },
    )
    .then(res => res.content)
}

/**
 * 拉取消息历史
 */
export const getAiChatListMsgHistory = (data: IParmasMsgHistory, ai_user_id: number) => {
  return request
    .post(`/platform/api/aichat/h5/listMsgHistory?ai_user_id=${ai_user_id}`, data, {
      headers: {
        Authorization: `Bearer ${getToken()}`,
      },
    })
    .then(res => res.content)
}

/**
 * 语音合成
 */
export const getAiChatTts = (text: string, ai_user_id: number) => {
  return request
    .post(
      '/platform/api/aichat/h5/tts',
      { text, ai_user_id },
      {
        headers: {
          Authorization: `Bearer ${getToken()}`,
        },
      },
    )
    .then(res => res.content)
}

/**
 * 会话状态
 * chat_time>=free_chat_time 不能发消息
 */
export const getChatStatus = (ai_user_id: number) => {
  return request
    .post(
      '/platform/api/aichat/h5/chatStatus',
      { ai_user_id },
      {
        headers: {
          Authorization: `Bearer ${getToken()}`,
        },
      },
    )
    .then(res => res.content)
}

/**拿音频文件的路径 */
export const getTtsContent = (url: string) => {
  return getFileRequest.get(url, {
    headers: {
      'Authorization': `Bearer ${getToken()}`,
      'Content-Type': 'application/json; application/octet-stream',
    },
    responseType: 'blob',
  })
}
